#define _CRT_SECURE_NO_WARNINGS 1

class Solution {
public:
    int deleteAndEarn(vector<int>& nums) {
        sort(nums.begin(), nums.end());
        unordered_map<int, int> hash;
        for (auto& e : nums) hash[e] += e;
        nums.resize(unique(nums.begin(), nums.end()) - nums.begin());
        int n = nums.size();
        if (n == 1)
            return hash[nums[0]];

        vector<int> dp(n);
        int tmp = 0;
        for (int i = 0; i < n; ++i)
        {
            dp[i] += hash[nums[i]];
            for (int j = 0; j < i; ++j)
            {
                if (nums[i] == nums[j] + 1 || nums[i] == nums[j] - 1) continue;
                tmp = max(tmp, dp[j]);
            }
            dp[i] += tmp;
            tmp = 0;
        }

        return max(dp[n - 1], dp[n - 2]);
    }
};